package logic

import (
	"context"
	"encoding/json"
	"renting-demo/goods_srv/goodsclient"

	"renting-demo/api/internal/svc"
	"renting-demo/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetProductLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetProductLogic {
	return &GetProductLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetProductLogic) GetProduct(req *types.GetProductReq) (resp *types.Data, err error) {
	// todo: add your logic here and delete this line
	res, err := l.svcCtx.GoodsServer.GetProduct(context.Background(), &goodsclient.GetProductReq{
		Page:   int64(req.Page),
		Search: req.Search,
	})
	if err != nil {
		return &types.Data{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	if len(res.Goods) == 0 {
		return &types.Data{
			Code:    500,
			Message: "查询失败",
		}, nil
	}

	var data string
	for _, v := range res.Goods {
		b, _ := json.Marshal(v)
		data += string(b)
	}

	return &types.Data{
		Code:    500,
		Message: "查询成功",
		Data:    map[string]string{"search": res.Search, "goods": data},
	}, nil
}
